<template>
  <div class="blog-page">
    <h1>博客内容</h1>
    
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else>
      <div class="blog-layout">
        <div class="blog-main">
          <div class="blog-featured" v-if="featuredPost">
            <img :src="featuredPost.image || defaultImage" :alt="featuredPost.title" class="featured-image">
            <div class="featured-content">
              <span class="blog-category">{{ featuredPost.category?.name || '未分类' }}</span>
              <h3 class="blog-title">{{ featuredPost.title }}</h3>
              <div class="blog-date">
                <i class="far fa-calendar-alt"></i> {{ formatDate(featuredPost.publishDate) }}
              </div>
              <p>{{ featuredPost.excerpt }}</p>
              <router-link :to="{ name: 'blog-detail', params: { id: featuredPost.id } }" class="cta-button">
                阅读全文
              </router-link>
            </div>
          </div>
          
          <div class="blog-list">
            <div v-for="post in blogPosts" :key="post.id" class="blog-card-horizontal">
              <img :src="post.image || defaultImage" :alt="post.title" class="blog-thumbnail">
              <div class="blog-card-content">
                <span class="blog-category">{{ post.category?.name || '未分类' }}</span>
                <h3 class="blog-title">{{ post.title }}</h3>
                <div class="blog-date">
                  <i class="far fa-calendar-alt"></i> {{ formatDate(post.publishDate) }}
                </div>
                <p>{{ post.excerpt }}</p>
                <router-link :to="{ name: 'blog-detail', params: { id: post.id } }" class="read-more">
                  阅读更多 <i class="fas fa-arrow-right"></i>
                </router-link>
              </div>
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination" v-if="totalPages > 1">
              <button 
                @click="changePage(currentPage - 1)" 
                :disabled="currentPage === 1"
                class="page-btn"
              >
                <i class="fas fa-chevron-left"></i>
              </button>
              
              <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
              
              <button 
                @click="changePage(currentPage + 1)" 
                :disabled="currentPage === totalPages"
                class="page-btn"
              >
                <i class="fas fa-chevron-right"></i>
              </button>
            </div>
          </div>
        </div>
        
        <div class="blog-sidebar">
          <div class="sidebar-widget">
            <h3 class="widget-title">搜索</h3>
            <div class="search-form">
              <input 
                type="text" 
                class="search-input" 
                placeholder="搜索文章..."
                v-model="searchQuery"
                @keyup.enter="searchArticles"
              >
              <button class="search-button" @click="searchArticles"><i class="fas fa-search"></i></button>
            </div>
          </div>
          
          <div class="sidebar-widget">
            <h3 class="widget-title">文章分类</h3>
            <ul class="categories-list">
              <li @click="filterByCategory('')" :class="{ 'active': selectedCategory === '' }">
                <span>全部分类</span>
                <span class="category-count">{{ totalArticles }}</span>
              </li>
              <li v-for="category in categories" 
                  :key="category.id" 
                  @click="filterByCategory(category.id)"
                  :class="{ 'active': selectedCategory === category.id }">
                <span>{{ category.name }}</span>
                <span class="category-count">{{ category.postCount }}</span>
              </li>
            </ul>
          </div>
          
          <div class="sidebar-widget">
            <h3 class="widget-title">热门文章</h3>
            <div v-for="post in popularPosts" :key="post.id" class="recent-post">
              <img :src="post.image || defaultImage" :alt="post.title" class="recent-post-img">
              <div class="recent-post-content">
                <router-link :to="{ name: 'blog-detail', params: { id: post.id } }" class="recent-post-title">
                  {{ post.title }}
                </router-link>
                <div class="recent-post-date">{{ formatDate(post.publishDate) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { articleService, categoryService } from '../services';

export default {
  setup() {
    // 状态
    const loading = ref(true);
    const blogPosts = ref([]);
    const featuredPost = ref(null);
    const popularPosts = ref([]);
    const categories = ref([]);
    const totalArticles = ref(0);
    
    // 搜索和筛选状态
    const searchQuery = ref('');
    const selectedCategory = ref('');
    
    // 分页状态
    const currentPage = ref(1);
    const totalPages = ref(1);
    const pageSize = 6;
    
    // 默认图片
    const defaultImage = 'https://images.unsplash.com/photo-1517694712202-14dd9538aa97?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1470&q=80';
    
    // 加载文章列表
    const loadArticles = async () => {
      try {
        loading.value = true;
        
        const params = {
          page: currentPage.value,
          limit: pageSize,
          published: true
        };
        
        if (searchQuery.value) {
          params.search = searchQuery.value;
        }
        
        if (selectedCategory.value) {
          params.category = selectedCategory.value;
        }
        
        const response = await articleService.getArticles(params);
        
        blogPosts.value = response.articles || [];
        totalPages.value = response.totalPages || 1;
        totalArticles.value = response.totalItems || 0;
        
        // 确保当前页不超过总页数
        if (currentPage.value > totalPages.value && totalPages.value > 0) {
          currentPage.value = totalPages.value;
          await loadArticles();
        }
      } catch (error) {
        console.error('加载文章列表失败:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 加载精选文章
    const loadFeaturedArticle = async () => {
      try {
        const response = await articleService.getFeaturedArticles();
        const featured = response.articles || [];
        
        if (featured.length > 0) {
          featuredPost.value = featured[0];
        }
      } catch (error) {
        console.error('加载精选文章失败:', error);
      }
    };
    
    // 加载热门文章
    const loadPopularPosts = async () => {
      try {
        const response = await articleService.getFeaturedArticles();
        popularPosts.value = (response.articles || []).slice(0, 3);
      } catch (error) {
        console.error('加载热门文章失败:', error);
      }
    };
    
    // 加载分类列表
    const loadCategories = async () => {
      try {
        const response = await categoryService.getAllCategories();
        categories.value = response.categories || [];
      } catch (error) {
        console.error('加载分类列表失败:', error);
      }
    };
    
    // 按分类筛选
    const filterByCategory = (categoryId) => {
      selectedCategory.value = categoryId;
      currentPage.value = 1;
      loadArticles();
    };
    
    // 搜索文章
    const searchArticles = () => {
      currentPage.value = 1;
      loadArticles();
    };
    
    // 切换页码
    const changePage = (page) => {
      if (page < 1 || page > totalPages.value) return;
      currentPage.value = page;
      loadArticles();
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    };
    
    // 初始化
    onMounted(async () => {
      await Promise.all([
        loadCategories(),
        loadFeaturedArticle(),
        loadPopularPosts()
      ]);
      
      await loadArticles();
    });
    
    return {
      loading,
      blogPosts,
      featuredPost,
      popularPosts,
      categories,
      totalArticles,
      searchQuery,
      selectedCategory,
      currentPage,
      totalPages,
      defaultImage,
      filterByCategory,
      searchArticles,
      changePage,
      formatDate
    };
  }
}
</script>

<style scoped>
.blog-page {
  margin-top: 40px;
}

.blog-layout {
  display: flex;
  gap: 40px;
  margin-top: 30px;
}

.blog-main {
  flex: 2;
}

.blog-sidebar {
  flex: 1;
}

/* 加载样式 */
.loading {
  text-align: center;
  padding: 50px 0;
}

.spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 精选文章 */
.blog-featured {
  display: flex;
  flex-direction: column;
  margin-bottom: 40px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: #fff;
}

.featured-image {
  width: 100%;
  height: 350px;
  object-fit: cover;
}

.featured-content {
  padding: 30px;
}

.blog-category {
  display: inline-block;
  padding: 5px 10px;
  background-color: #f8f9fa;
  border-radius: 20px;
  font-size: 14px;
  margin-bottom: 10px;
}

.blog-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 24px;
}

.blog-date {
  color: #6c757d;
  margin-bottom: 15px;
  font-size: 14px;
}

.blog-date i {
  margin-right: 5px;
}

.cta-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  margin-top: 15px;
  transition: background-color 0.3s;
}

.cta-button:hover {
  background-color: #0069d9;
}

/* 博客列表 */
.blog-card-horizontal {
  display: flex;
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: #fff;
}

.blog-thumbnail {
  width: 200px;
  height: 200px;
  object-fit: cover;
}

.blog-card-content {
  padding: 20px;
  flex: 1;
}

.read-more {
  color: #007bff;
  text-decoration: none;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.read-more:hover {
  text-decoration: underline;
}

/* 分页控件 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #ced4da;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  color: #6c757d;
  cursor: not-allowed;
}

.page-info {
  font-weight: 500;
}

/* 侧边栏 */
.sidebar-widget {
  margin-bottom: 40px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.widget-title {
  margin-top: 0;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

/* 搜索框 */
.search-form {
  display: flex;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
}

.search-button {
  padding: 0 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

/* 分类列表 */
.categories-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.categories-list li {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.3s;
}

.categories-list li:last-child {
  border-bottom: none;
}

.categories-list li:hover,
.categories-list li.active {
  color: #007bff;
}

.category-count {
  background-color: #f8f9fa;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

/* 热门文章 */
.recent-post {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.recent-post:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.recent-post-img {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.recent-post-title {
  display: block;
  margin-bottom: 5px;
  color: #212529;
  text-decoration: none;
  font-weight: 500;
}

.recent-post-title:hover {
  color: #007bff;
}

.recent-post-date {
  color: #6c757d;
  font-size: 12px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .blog-layout {
    flex-direction: column;
  }
  
  .blog-card-horizontal {
    flex-direction: column;
  }
  
  .blog-thumbnail {
    width: 100%;
    height: 200px;
  }
}
</style> 